import { defineStore } from 'pinia'
import http from '../utils/http'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: JSON.parse(localStorage.getItem('user') || 'null'),
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    userInfo: (state) => state.user,
  },
  
  actions: {
    async login(credential, password) {
      try {
        const response = await http.post('/auth/login', {
          credential,
          password
        })
        
        const { access_token, user } = response
        
        // 保存到状态和本地存储
        this.token = access_token
        this.user = user
        
        localStorage.setItem('token', access_token)
        localStorage.setItem('user', JSON.stringify(user))
        
        return { success: true }
      } catch (error) {
        return {
          success: false,
          message: error.response?.data?.message || '登录失败，请检查您的凭证'
        }
      }
    },
    
    async register(userData) {
      try {
        const response = await http.post('/auth/register', userData)
        return { success: true, data: response }
      } catch (error) {
        return {
          success: false,
          message: error.response?.data?.message || '注册失败，请稍后再试'
        }
      }
    },
    
    async updateProfile(userData) {
      try {
        const response = await http.put('/user/profile', userData)
        
        // 更新状态和本地存储
        this.user = response.user
        localStorage.setItem('user', JSON.stringify(response.user))
        
        return { success: true, data: response }
      } catch (error) {
        return {
          success: false,
          message: error.response?.data?.message || '更新个人信息失败'
        }
      }
    },
    
    async changePassword(oldPassword, newPassword) {
      try {
        const response = await http.put('/auth/change-password', {
          old_password: oldPassword,
          new_password: newPassword
        })
        
        return { success: true, message: response.message }
      } catch (error) {
        return {
          success: false,
          message: error.response?.data?.message || '修改密码失败'
        }
      }
    },
    
    logout() {
      // 清除状态和本地存储
      this.token = ''
      this.user = null
      
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    }
  }
})